package com.zjut.an.webclass.dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.zjut.an.util.module.PageModule;



/**
 * A data access object (DAO) providing persistence and search support for
 * AnWebclass entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see com.zjut.an.webclass.dao.AnWebclass
 * @author MyEclipse Persistence Tools
 */

public class AnWebclassDAO extends HibernateDaoSupport {
	private static final Logger log = LoggerFactory
			.getLogger(AnWebclassDAO.class);
	// property constants
	public static final String WC_ID = "wcId";
	public static final String WC_NAME = "wcName";
	public static final String WC_NOTE = "wcNote";
	public static final String WC_FOLDER = "wcFolder";
	public static final String WC_PARENT = "wcParent";
	public static final String WC_TYPE = "wcType";
	public static final String WC_VIEWPOWER = "wcViewpower";
	public static final String WC_SHOWTYPE = "wcShowtype";
	public static final String WC_LISTTYPE = "wcListtype";
	public static final String WC_MENUVIEW = "wcMenuview";
	public static final String WC_URL = "wcUrl";
	public static final String WC_ADMIN = "wcAdmin";
	public static final String WC_ORDER = "wcOrder";

	public void sort(Criteria criteria, String sort, String order) {
		if (sort!=null && order!=null) {
			System.out.println(sort + order + " sort !!!!!!!!!!!!!!!!");
			if (order.equals("asc")) {
				criteria.addOrder(Order.asc(sort));
			} else {
				criteria.addOrder(Order.desc(sort));
			}
		} else {
			criteria.addOrder(Order.desc(WC_ID));
		}
	}

	protected void initDao() {
		// do nothing
	}

	public void save(AnWebclass transientInstance) {
		log.debug("saving AnWebclass instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void update(AnWebclass transientInstance) {
		log.debug("updating AnWebclass instance");
		try {
			getHibernateTemplate().update(transientInstance);
			log.debug("update successful");
		} catch (RuntimeException re) {
			log.error("update failed", re);
			throw re;
		}
	}

	public void delete(AnWebclass persistentInstance) {
		log.debug("deleting AnWebclass instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public AnWebclass findById(java.lang.Integer id) {
		log.debug("getting AnWebclass instance with id: " + id);
		try {
			AnWebclass instance = (AnWebclass) getHibernateTemplate().get(
					"com.zjut.an.webclass.dao.AnWebclass", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(AnWebclass instance) {
		log.debug("finding AnWebclass instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding AnWebclass instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from AnWebclass as model where model."
					+ propertyName + "= ? order by wcOrder desc, wcId desc";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByWcName(Object wcName) {
		return findByProperty(WC_NAME, wcName);
	}

	public List findByWcNote(Object wcNote) {
		return findByProperty(WC_NOTE, wcNote);
	}

	public List findByWcFolder(Object wcFolder) {
		return findByProperty(WC_FOLDER, wcFolder);
	}

	public List findByWcParent(Object wcParent) {
		return findByProperty(WC_PARENT, wcParent);
	}

	public List findByWcType(Object wcType) {
		return findByProperty(WC_TYPE, wcType);
	}

	public List findByWcViewpower(Object wcViewpower) {
		return findByProperty(WC_VIEWPOWER, wcViewpower);
	}

	public List findByWcShowtype(Object wcShowtype) {
		return findByProperty(WC_SHOWTYPE, wcShowtype);
	}

	public List findByWcListtype(Object wcListtype) {
		return findByProperty(WC_LISTTYPE, wcListtype);
	}

	public List findByWcMenuview(Object wcMenuview) {
		return findByProperty(WC_MENUVIEW, wcMenuview);
	}

	public List findByWcUrl(Object wcUrl) {
		return findByProperty(WC_URL, wcUrl);
	}

	public List findByWcAdmin(Object wcAdmin) {
		return findByProperty(WC_ADMIN, wcAdmin);
	}

	public List findByWcOrder(Object wcOrder) {
		return findByProperty(WC_ORDER, wcOrder);
	}

	public List findAll() {
		log.debug("finding all AnWebclass instances");
		try {
			String queryString = "from AnWebclass order by wcParent";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List findByHql(final int pageNumber ,final int pageSize, final String hql, final Object[] values){
		log.debug("finding AcAlumni instance by hql");
	    return (List<AnWebclass>) super.getHibernateTemplate().execute(new HibernateCallback(){
	        public Object doInHibernate(Session session) throws HibernateException, SQLException {
	            Query query=session.createQuery(hql);
	            if (values != null) {// 为hql语句传入参数
					for (int i = 0; i < values.length; i++) {
						query.setParameter(i, values[i]);
					}
				}
	            return query.setFirstResult((pageNumber-1)*pageSize).setMaxResults(pageSize).list();
	        }
	    });
	}

	@SuppressWarnings("unchecked")
	public int findCountByHql(final String hql, final Object[] values) {
		log.debug("finding the number of AnWebclass instance");
		try {
			return (Integer) super.getHibernateTemplate().execute(new HibernateCallback(){
		        public Object doInHibernate(Session session) throws HibernateException, SQLException {
		            Query query=session.createQuery(hql);
		            if (values != null) {// 为hql语句传入参数
						for (int i = 0; i < values.length; i++) {
							query.setParameter(i, values[i]);
						}
					}
					return ((Long)query.uniqueResult()).intValue();
		        }
		    });
		} catch (RuntimeException re) {
			log.error("find the number of AnWebclass instance failed", re);
			throw re;
		}
	}
	
	@SuppressWarnings("unchecked")
	public PageModule findByInstance(final int pageNumber ,final int pageSize, String sort, String order, final AnWebclass obj){
		try {
			int startIndex = (pageNumber - 1) * pageSize;
			Session session = getHibernateTemplate().getSessionFactory().openSession();
			List list;
			Criteria criteria = session.createCriteria(AnWebclass.class);
			
			if (!isEmpty(obj.getWcName())) {
				criteria.add(Restrictions.like(WC_NAME, obj.getWcName(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getWcNote())) {
				criteria.add(Restrictions.like(WC_NOTE, obj.getWcNote(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getWcFolder())) {
				criteria.add(Restrictions.like(WC_FOLDER, obj.getWcFolder(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getWcName())) {
				criteria.add(Restrictions.like(WC_NAME, obj.getWcName(),MatchMode.ANYWHERE));
			}
			if (null != obj.getWcParent()) {
				criteria.add(Restrictions.eq(WC_PARENT, obj.getWcParent()));
			}
			if (!isEmpty(obj.getWcType())) {
				criteria.add(Restrictions.like(WC_TYPE, obj.getWcType(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getWcViewpower())) {
				criteria.add(Restrictions.like(WC_VIEWPOWER, obj.getWcViewpower(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getWcShowtype())) {
				criteria.add(Restrictions.like(WC_SHOWTYPE, obj.getWcShowtype(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getWcListtype())) {
				criteria.add(Restrictions.like(WC_LISTTYPE, obj.getWcListtype(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getWcMenuview())) {
				criteria.add(Restrictions.like(WC_MENUVIEW, obj.getWcMenuview(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getWcUrl())) {
				criteria.add(Restrictions.like(WC_URL, obj.getWcUrl(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getWcAdmin())) {
				criteria.add(Restrictions.like(WC_ADMIN, obj.getWcAdmin(),MatchMode.ANYWHERE));
			}
			if (null != obj.getWcOrder()) {
				criteria.add(Restrictions.eq(WC_ORDER, obj.getWcOrder()));
			}
			this.sort(criteria, sort, order);
			
			criteria.setFirstResult(startIndex);
			criteria.setMaxResults(pageSize);
			list = criteria.list();
			session.close();
			return new PageModule(pageNumber, pageSize, countByInstance(obj), list);
		} catch (RuntimeException re) {
			log.error("findByInstance failed", re);
			throw re;
		}
	}
	
	public int countByInstance(final AnWebclass obj) {
		log.debug("finding the number of AnWebclass instance");
		try {
			int count = 0;
			Session session = getHibernateTemplate().getSessionFactory().openSession();
			Criteria criteria = session.createCriteria(AnWebclass.class);

			if (!isEmpty(obj.getWcName())) {
				criteria.add(Restrictions.like(WC_NAME, obj.getWcName(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getWcNote())) {
				criteria.add(Restrictions.like(WC_NOTE, obj.getWcNote(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getWcFolder())) {
				criteria.add(Restrictions.like(WC_FOLDER, obj.getWcFolder(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getWcName())) {
				criteria.add(Restrictions.like(WC_NAME, obj.getWcName(),MatchMode.ANYWHERE));
			}
			if (null != obj.getWcParent()) {
				criteria.add(Restrictions.eq(WC_PARENT, obj.getWcParent()));
			}
			if (!isEmpty(obj.getWcType())) {
				criteria.add(Restrictions.like(WC_TYPE, obj.getWcType(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getWcViewpower())) {
				criteria.add(Restrictions.like(WC_VIEWPOWER, obj.getWcViewpower(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getWcShowtype())) {
				criteria.add(Restrictions.like(WC_SHOWTYPE, obj.getWcShowtype(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getWcListtype())) {
				criteria.add(Restrictions.like(WC_LISTTYPE, obj.getWcListtype(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getWcMenuview())) {
				criteria.add(Restrictions.like(WC_MENUVIEW, obj.getWcMenuview(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getWcUrl())) {
				criteria.add(Restrictions.like(WC_URL, obj.getWcUrl(),MatchMode.ANYWHERE));
			}
			if (null != obj.getWcOrder()) {
				criteria.add(Restrictions.eq(WC_ORDER, obj.getWcOrder()));
			}
			count = (Integer) criteria.setProjection(Projections.rowCount()).uniqueResult();
			session.close();
			return count;
		} catch (RuntimeException re) {
			log.error("find the number of AnWebclass instance failed", re);
			throw re;
		}
	}
	
	private boolean isEmpty(String value) {
		if (value==null || value.trim().length()==0) {
			return true;
		}
		return false;
	}

	public AnWebclass merge(AnWebclass detachedInstance) {
		log.debug("merging AnWebclass instance");
		try {
			AnWebclass result = (AnWebclass) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(AnWebclass instance) {
		log.debug("attaching dirty AnWebclass instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(AnWebclass instance) {
		log.debug("attaching clean AnWebclass instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static AnWebclassDAO getFromApplicationContext(ApplicationContext ctx) {
		return (AnWebclassDAO) ctx.getBean("AnWebclassDAO");
	}
}